<template>
  <div class="rec_page">
    <user-card></user-card>
    <!-- <div class="tab_box"> -->
    <tab :line-width="3.5" custom-bar-width="30px" active-color="#131A2A" bar-active-color="#448EFF"
         default-color="#9CA6BA">
      <tab-item selected @on-item-click="tabItemClick">全部</tab-item>
      <tab-item @on-item-click="tabItemClick">待支付</tab-item>
      <tab-item @on-item-click="tabItemClick">已挂号</tab-item>
      <!--      <tab-item @on-item-click="tabItemClick">已取号</tab-item>-->
    </tab>
    <!-- </div> -->
    <template v-if="noData">
      <div class="noresult">
        <img src="@/assets/img/img_no results@2x.png" alt=""/>
        <div>无数据</div>
      </div>
    </template>
    <template v-else>

      <div v-if="tabItemShow == '0'" class="tab_item_box">
        <div class="reg_item" @click="goRegDetails(item)" v-for="(item, index) in platformRegList">
          <div class="reg_item_1">
            <template v-if="item.status == '2'">
              <div style="font-weight: bold;"> 预约时间：{{ item.regDate + " " + item.hospGetregDate }}
              </div>
              <div style="color: #f72d23">待支付</div>
            </template>
            <template v-if="item.status == '6'">
              <div>支付时间：{{ item.payTime }}</div>
              <div style="color: #5fc13d">已预约</div>
            </template>
            <template v-if="item.status == '3'">
              <div>取号时间：{{ item.updateTime }}</div>
              <div style="color: #a4adbe">已取号</div>
            </template>
            <!-- 4未支付取消 5已支付已退款取消 -->
            <template v-if="item.status == '4' || item.status == '5'">
              <div>取消时间：{{ item.cancelDate }}</div>
              <div style="color: #a4adbe">已取消</div>
            </template>
          </div>
          <div style="font-size: 1rem; color: #101010">
            科室：{{ item.deptName }}
          </div>
          <div style="font-size: 0.875rem; color: #101010">
            医生：{{ item.doctorName }}
          </div>
          <div style="font-size: 0.875rem">
            总费用：{{ item.totalFee / 100 }}元
          </div>
          <div>
            下单时间：{{ item.createTime }}
            <!-- 预约时间：{{ item.regDate + " " + item.hospGetregDate }} -->
            <!--          {{ item.hospGetregDate | timefun }}-->
          </div>
          <div class="reg_item_2" v-if="item.status == '2'">
            <div class="btn2" @click.stop="CancelRegLock(item)">取消挂号</div>
            <div class="btn2" @click.stop="goPayment(item)">去支付</div>
          </div>
          <div class="reg_item_2" v-if="item.status == '6'">
            <div class="btn2" @click.stop="RegCancel(item)">取消挂号</div>
            <!-- <div class="btn2">去支付</div> -->
          </div>
        </div>
        <div class="reg_item" v-for="(item, index) in hisRegList" @click="goRegDetailsOther(item)">
          <div class="reg_item_1">
            <div style="font-weight: bold;">预约时间：{{ item.regDate }}</div>
            <div style="color: #5fc13d" v-if="item.validFlag == 1">已挂号</div>
            <div style="color: #a4adbe" v-if="item.validFlag == 0">已退号</div>
          </div>
          <div style="font-size: 1rem; color: #101010">
            科室：{{ item.deptname }}
          </div>
          <div style="font-size: 0.875rem; color: #101010">
            医生：{{ item.decpname }}
          </div>
          <div style="font-size: 0.875rem; color: #101010">
            挂号方式：{{ item.pactname }}
          </div>
          <div style="font-size: 0.875rem">
            总费用：{{ item.regFee }}元
          </div>
          <div>
            支付时间：{{ item.operDate }}

            <!-- {{ item.timeFlag == 1 ? "上午 08:00-11:30" : "下午 13:00-16:30" }} -->
          </div>
          <div class="reg_item_2" v-if="item.validFlag == 1">
            <!-- 判断预约日期是否在今日当日 -->
            <template v-if="$moment(item.regDate).isAfter($moment().format('YYYY-MM-DD'), 'day')">

              <div class="btn2" @click.stop="RegCancel(item)" v-if="item.pactname == '智慧医院'">取消挂号</div>

            </template>

            <!-- <div class="btn2">去支付</div> -->
          </div>
        </div>
      </div>
      <div v-if="tabItemShow == '1'" class="tab_item_box">
        <div class="reg_item" v-for="(item, index) in platformRegList" @click="goRegDetails(item)">
          <div class="reg_item_1">
            <div style="font-weight: bold;">预约时间：{{ item.regDate + " " + item.hospGetregDate }}</div>
            <div style="color: #f72d23">待支付</div>
          </div>
          <div style="font-size: 1rem; color: #101010">
            科室：{{ item.deptName }}
          </div>
          <div style="font-size: 0.875rem; color: #101010">
            医生：{{ item.doctorName }}
          </div>
          <div style="font-size: 0.875rem">
            总费用：{{ item.totalFee / 100 }}元
          </div>
          <div>
            下单时间：{{ item.createTime }}


            <!--          {{ item.hospGetregDate | timefun }}-->
          </div>
          <div class="reg_item_2">
            <div class="btn2" @click.stop="CancelRegLock(item)">取消挂号</div>
            <div class="btn2" @click.stop="goPayment(item)">去支付</div>
          </div>
        </div>
      </div>
      <div v-if="tabItemShow == '2'" class="tab_item_box">
        <div class="reg_item" v-for="(item, index) in hisRegList" @click="goRegDetailsOther(item)"
             v-if="item.validFlag == 1">
          <div class="reg_item_1">
            <div style="font-weight: bold;">预约时间：{{ item.regDate }}</div>
            <div style="color: #5fc13d" v-if="item.validFlag == 1">已挂号</div>
            <div style="color: #a4adbe" v-if="item.validFlag == 0">已退号</div>
          </div>
          <div style="font-size: 1rem; color: #101010">
            科室：{{ item.deptname }}
          </div>
          <div style="font-size: 0.875rem; color: #101010">
            医生：{{ item.decpname }}
          </div>
          <div style="font-size: 0.875rem; color: #101010">
            挂号方式：{{ item.pactname }}
          </div>
          <div style="font-size: 0.875rem">
            总费用：{{ item.regFee }}元
          </div>
          <div>
            支付时间：{{ item.operDate }}

            <!-- {{ item.timeFlag == 1 ? "上午 08:00-11:30" : "下午 13:00-16:30" }} -->
          </div>
          <div class="reg_item_2" v-if="item.validFlag == '1'">
            <!-- 判断预约日期是否在今日当日 -->
            <template v-if="$moment(item.regDate).isAfter($moment().format('YYYY-MM-DD'), 'day')">

              <div class="btn2" @click.stop="RegCancel(item)" v-if="item.pactname == '智慧医院'">取消挂号</div>

            </template>

            <!-- <div class="btn2">去支付</div> -->
          </div>
        </div>
      </div>

    </template>
  </div>
</template>
<script>
import {getOrderRegList, cancelReg, orderRefund, payCreate, queryOrderStatus} from "@/api/api";
import userCard from "@/components/userCard.vue";
import {Tab, TabItem} from "vux";
import Vue from "vue";

export default {
  components: {
    userCard,
    Tab,
    TabItem,
  },
  data() {
    return {
      isPayClick: false,
      noData: true,
      tabItemShow: "0",
      userInfo: {},
      reserveList: [],
      platformRegList: [],
      hisRegList: [],
      endDate: this.$moment().format('YYYY-MM-DD'),
      count: 0

    };
  },
  created() {
    if (window.localStorage.getItem("userInfo")) {
      this.userInfo = JSON.parse(window.localStorage.getItem("userInfo"));
    } else {
      this.userInfo = JSON.parse(
        window.localStorage.getItem("defaultUserInfo")
      );
    }
    this.GetReserveList();
  },
  methods: {
    // 获取挂号记录列表
    GetReserveList(status) {
      var data = {
        // status: "",
        hospPatientId: this.userInfo.hospPatientId,
        idcardType: "",
        idcardNo: this.userInfo.idNo,
        cardNo: "",
        name: this.userInfo.name,
        operMobile: this.userInfo.mobile,
        startDate: "1970-01-01",
        endDate: this.endDate
      };
      getOrderRegList(data).then((res) => {
        if (res.code == 200) {
          this.reserveList = res.data;
          this.platformRegList = res.data.platformRegList // 未支付订单
          this.hisRegList = res.data.hisRegList //其余订单
          // 判断是否显示暂无数据
          if (this.tabItemShow == '0') {
            if (this.platformRegList.length > 0 || this.hisRegList.length > 0) {
              this.noData = false;
            } else {
              this.noData = true
            }

          } else if (this.tabItemShow == '1') {
            if (this.platformRegList.length > 0) {
              this.noData = false;
            } else {
              this.noData = true
            }

          } else if (this.tabItemShow == '2') {
            if (this.hisRegList.length > 0) {
              this.hisRegList.forEach(element => {
                if (element.validFlag == 1) {
                  this.noData = false;

                }
              });

            } else {
              this.noData = true
            }

          }
        }
      });
    },
    // 待支付 取消挂号
    CancelRegLock(item) {
      const that = this;
      const data = {
        hosId: "",
        orderId: item.orderId,
        hospPatientId: this.userInfo.hospPatientId,
        cancelRemark: "用户主动取消",
      };
      that.$vux.confirm.show({
        // 组件除show外的属性
        title: "提示",
        content: "是否确认取消挂号?",
        onCancel() {
        },
        onConfirm() {
          cancelReg(data).then((res) => {
            if (res.code == 200) {
              that.$vux.toast.show("取消挂号成功");
              setTimeout(() => {
                that.GetReserveList();
              }, 2000);
            } else {
              that.$vux.toast.show(res.message);
            }
          });
        },
      });
    },
    //已完成 取消挂号
    RegCancel(item) {
      const that = this;
      const data = {
        orderId: item.orderId,
      };
      that.$vux.confirm.show({
        // 组件除show外的属性
        title: "提示",
        content: "是否确认取消挂号?",
        onCancel() {
        },
        onConfirm() {
          orderRefund(data).then((res) => {
            if (res.code == 200) {
              that.$vux.toast.show("取消挂号成功");
              // setTimeout(() => {
              //   that.GetReserveList();
              // }, 1000);
              setTimeout(() => {
                that.GetReserveList();
              }, 2000);
            } else {
              that.$vux.toast.show(res.message);
            }
          });
        },
      });
    },
    // 去支付
    goPayment(item) {
      if (this.isPayClick) {
        console.log("请勿重复支付!")
        return;
      }
      this.$vux.loading.show({text: '请求支付信息...'});
      this.isPayClick = true;
      setTimeout(function () {
        this.isPayClick = false;
      }, 2000);
      const that = this
      that.payCreate(item.orderId)
      // this.$router.push({ path: "/payment", query: paydata });
    },
    // 获取微信支付配置
    payCreate(hospOrderId) {
      const that = this;
      payCreate({
        orderType: "1",
        orderId: hospOrderId,
        openId: window.localStorage.getItem("openId"),
      }).then((res) => {
        this.isPayClick = false;
        if (res.code == 200) {
          // 调起微信支付
          window.localStorage.setItem("PAY_ORDER_ID", hospOrderId);
          that.wxPay(res.data, hospOrderId);
        } else {
          window.localStorage.setItem("PAY_ORDER_ID", "");
          this.GetReserveList();
          alert(res.message);
        }
      });
    },
    // 发起微信支付
    wxPay(data, hospOrderId) {
      this.$vux.loading.hide();
      const that = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: data.appId, //公众号名称，由商户传入
          timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: data.nonceStr, //随机串
          package: data.package,
          signType: data.signType, //微信签名方式：
          paySign: data.paySign, //微信签名
        },
        function (response) {
          //TODO 应该再进行一次查单验证来保证支付成功
          if (response.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            // res.err_msg将在用户支付成功后返回get_brand_wcpay_request:ok，但并不保证它绝对可靠。
            // window.location.href = "http://ydkq.eaccessy.com/registration_record";
            that.$vux.loading.show()
            that.queryOrderStatusFun(hospOrderId)
          } else {
            // alert("支付失败");
            that.$vux.toast.show("支付失败");
            that.$router.push('/registration_record');
          }
        }
      );
    },
    queryOrderStatusFun(orderId) {
      queryOrderStatus({
        orderId, //订单号
        "orderType": "1" //1:挂号 2:缴费
      }).then(res => {
        this.count++
        // 轮询6次
        if (this.count < 6) {
          if (res.code == 200) {
            this.$vux.loading.hide()
            alert("挂号成功")
            this.$router.push({
              path: "/registration_record",
              query: {
                orderId,
                pactname: "智慧医院"
              },
            });

            return
          } else if (res.code == 400) {
            if (res.message == 'NOTIFY_HIS_ERROR') {
              alert("通知his失败");
              this.$vux.loading.hide()
              this.count = 0
              return
            } else {
              setTimeout(() => {
                this.queryOrderStatusFun(orderId)
              }, 2000)
            }

          }
        } else {
          alert("通知his失败");
          this.$vux.loading.hide()
          this.count = 0
          return
        }

      })
    },
    tabItemClick(e) {
      this.tabItemShow = e;
      if (this.tabItemShow == '0') {
        if (this.platformRegList.length > 0 || this.hisRegList.length > 0) {
          this.noData = false;
        } else {
          this.noData = true
        }

      } else if (this.tabItemShow == '1') {
        if (this.platformRegList.length > 0) {
          this.noData = false;
        } else {
          this.noData = true
        }

      } else if (this.tabItemShow == '2') {

        if (this.hisRegList.length > 0) {
          this.hisRegList.forEach(element => {
            if (element.validFlag == 1) {
              this.noData = false;

            }
          });

        } else {
          this.noData = true
        }

      }
    },
    goRegDetails(item) {
      item.pactname = "智慧医院"
      switch (item.status) {
        // 未支付已取消
        case "4":
          this.$router.push({
            path: "/registration_record_appo",
            query:
            item

          });
          break;
        // 待支付
        case "2":
          this.$router.push({
            path: "/registration_record_unpaid",
            query:
            item

          });
          break;
        // 已支付已退款
        case "5":
          this.$router.push({
            path: "/registration_record_appo",
            query:
            item

          });
          break;
        // 已预约
        case "6":
          this.$router.push({
            path: "/registration_record_appo",
            query:
            item

          });
          break;
        // 已取号
        case "3":
          this.$router.push({
            path: "/registration_record_take",
            query:
            item

          });
          break;
        default:
          break;
      }
    },
    goRegDetailsOther(item) {
      // 1 已预约 0 已退号
      this.$router.push({
        path: "/registration_record_appo",
        query:
        item,
      });

    },
  },
  filters: {
    timefun(time) {
      var newTime = time.slice(0, 2) + ":" + time.slice(2);
      newTime =
        newTime.slice(0, newTime.length - 2) +
        ":" +
        newTime.slice(newTime.length - 2);
      return newTime;
    },
  },
};
</script>
<style scoped>
.rec_page {
  height: 100vh;
  overflow: hidden;
}

.tab_item_box {
  background-color: #f7fafd;
  width: calc(100% - 2rem);
  height: calc(100% - 150px);
  padding: 1rem;
  overflow-y: scroll;
}

.reg_item {
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 0px 0.9375rem 0px rgba(174, 206, 254, 0.3);
  border-radius: 0.375rem;
  width: calc(100% - 1.875rem);
  padding: 1.0625rem 0.9375rem 0.8125rem 0.9375rem;
  color: #a4adbe;
  font-size: 0.875rem;
  margin-bottom: 0.75rem;
}

.reg_item > div {
  line-height: 1.5rem;
}

.reg_item_1 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 1rem;
  border-bottom: 0.0625rem solid #e7ecf5;
  margin-bottom: 0.9375rem;
}

.reg_item_2 {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  /* margin-top: 0.9375rem; */
}

.reg_item_2 > div {
  width: 5.625rem;
  height: 1.875rem;

  border-radius: 0.1875rem;
  text-align: center;
  line-height: 1.875rem;
  font-size: 0.9375rem;
}

.reg_item_2 .btn1 {
  border: 0.0625rem solid rgba(164, 173, 190, 1);
  color: #a4adbe;
}

.reg_item_2 .btn2 {
  border: 0.0625rem solid rgba(68, 142, 255, 1);
  color: #448eff;
  margin-left: 0.75rem;
}


.noresult {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-flow: column;
  height: 31.25rem;

}

.noresult img {
  display: block;
  width: 12.5rem;
  height: 9.75rem;
}
</style>
